import Taro, { Component } from '@tarojs/taro';
import { View, Swiper } from '@tarojs/components';
import './index.scss';
import { timeFormat, fullImgUrl } from '../../utils/utils';
import CloseIcon from '../tip-banner/img/close.png';
import CardRemind from '../tip-banner/img/card-remind.png';
import CardButton from '../tip-banner/img/card-btn.png';
import CardItemBg from '../tip-banner/img/card-item-bg.png';
import CardItemBgHide from '../tip-banner/img/card-item-bg-hide.png';
import { list, shareCard,getUserCardCount } from '../../services/electronicCard';
import { purchaseGood } from '../../services/goods';
import CardBg from '../tip-banner/img/electronic_card_bg.png';


export default class Index extends Component {

  config = {
    navigationBarTitleText: ''
  }


  state = {
    setting: Taro.getStorageSync('setting'),
    cardRecordList: [],
    isSHowCard: false,
    cardTotal: Taro.getStorageSync('card_count'),
    WillExpireCardTotal: Taro.getStorageSync('will_expire_card_count'),
    current: 0,
    isShowSwiper: false,
    isShowHomeTip: Taro.getStorageSync('setting').is_home_tip,
    cardIndex: 0,
    tipIndex: 0,
    isShowDots: true,
  }

  componentWillMount() {
    // const userInfo = Taro.getStorageSync('userInfo') || null;
    // if (userInfo === null) {
    //   const delay = 3000; // 3秒
    //   const timer = setTimeout(() => {
    //     // 等待3秒，等待接口完成用户信息获取后，重新赋值一次用户信息
    //     this.setState({'setting': Taro.getStorageSync('setting')})
    //     this.setState({'userInfo': Taro.getStorageSync('userInfo')})
    //     getUserCardCount().then((res) => {
    //       // 设置电子卡券数量，以判断是否展示 红点
    //       Taro.setStorageSync('card_count', res.total);
    //       Taro.setStorageSync('will_expire_card_count', res.will_expire);
    //       this.setState({
    //         cardTotal: res.total,
    //         isShowHomeTip: Taro.getStorageSync('setting').is_home_tip
    //       })
    //       this.dealInitData();
    //     });
        
    //   }, delay);
    //   // 清除定时器以防止内存泄漏
    //   return () => {
    //     clearTimeout(timer);
    //   };
    // }
  }
  componentDidMount() {
    this.dealInitData();
  }

  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  componentDidShow() { }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  close() {
    this.props.onClose();
  }

  dealInitData() {
    const { cardTotal, isShowHomeTip } = this.state;
    if (!isShowHomeTip) {
      this.setState({ isShowDots: false })
    }
    if (cardTotal > 0 || isShowHomeTip) {
      this.setState({
        isShowSwiper: true
      });
    } else {
      this.close();
    }

    if (cardTotal > 0) {
      this.setState({
        isShowSwiper: true,
        isSHowCard: true,
        cardIndex: 0,
        tipIndex: 1
      });
    }
  }

  async getCardList() {
    await list({
      page: 1,
      page_number: 2,
      card_status: 0,
    }).then(res => {
      if (res.total > 0) {
        let list = res.list;
        if (res.total == 1) {
          list = list.concat(res.list)
        }
        this.state.isSHowCard = true;
        this.state.isShowSwiper = true;
        this.setState({
          cardRecordList: list,
          cardTotal: res.total,
          isShowSwiper: true,
          cardIndex: 0,
          tipIndex: 1
        });
      } else {
        // 没卡。没首页弹窗，调用关闭
        if (this.state.isShowHomeTip == false) {
          this.close();
        }
      }
    })
  }

  goShop(goods_id, electronic_card_id) {
    // 跳转到兑换商场
    console.log('使用——兑换商场')
    purchaseGood({
      sku_id: 0,
      goods_id: goods_id,
      num: 1,
      electronic_card_id: electronic_card_id,
    }).then(res => {
      Taro.navigateTo({
        url: `/subPackageWork/pages/electronic-settlement/index`
      })
    })
  }

  handleImageLoad = () => {
    // 图片加载完成后，绑定点击事件
    const query = Taro.createSelectorQuery();
    query.select('#my-image')
      .boundingClientRect()
      .exec(res => {
        const imageRect = res[0];
        // 绑定点击事件
        imageRect.onClick = this.goMyCard;
      });
  };
  onShareAppMessage(res) {
    let data = res.target.dataset.item; //取到传入的参数
    console.log(data)
    let pathUrl = `/subPackageWork/pages/electronic-lp/index?card_id=${data.id}&initiator_id=${this.state.userInfo.id}`;
    console.log(pathUrl)

    shareCard({
      card_id: data.id
    }).then(res => {

    }).catch((err) => {
      if (showToast && err) {
        Taro.showToast({
          title: err.data,
          icon: 'none'
        })
      }
    })
    return {
      title: `${data.has_goods.goods_name}`,
      path: pathUrl,
      imageUrl: `${fullImgUrl(data.has_goods.share_image)}`,
    };
  }

  goMyCard() {
    Taro.redirectTo({
      url: '/subPackageWork/pages/electronic-card/index'
    });
  }

  //swiper滑动事件
  swiperChange = (e) => {
    this.setState({
      current: e.detail.current
    })
  }

  render() {
    const { setting, isShowSwiper, isSHowCard, isShowHomeTip, cardIndex, tipIndex, isShowDots, cardRecordList, cardTotal, WillExpireCardTotal, current } = this.state;
    return (
      <View className="container">
        {isShowSwiper &&
          <Swiper
            className="swiper-container"
            current={current}
            onChange={this.swiperChange}
            next-margin="70rpx"
            previous-margin="70rpx"
            indicatorColor='#B2B2B2'
            indicatorActiveColor='#DDD'
            circular
            autoplay
            indicatorDots={isShowDots}
            animation
          >
            {isSHowCard &&
              <SwiperItem className={`swiper-item ${cardIndex} ${current} ${current == cardIndex ? "swiper-item-active" : ""}`}>
                <View className="swiper-item-box">
                  <Image className='card-item-bg' src={CardRemind} onClick={() => this.goMyCard()} />
                  <View className='card-remind-h3' style='top:55%'>您有<Text className='card-remind-text'>{cardTotal < 10 ? "0" + cardTotal : cardTotal}</Text>张卡券等待使用</View>
                  {WillExpireCardTotal > 0 && <View className='card-remind-h3' style='top:61%'>其中<Text className='card-remind-text'>{WillExpireCardTotal < 10 ? "0" + WillExpireCardTotal : WillExpireCardTotal}</Text>张卡券即将过期</View>}
                  <Image onClick={this.close} className="colse-card" src={CloseIcon} />
                </View>
              </SwiperItem>
            }

            {isShowHomeTip &&
              <SwiperItem className={`swiper-item ${tipIndex} ${current} ${current == tipIndex ? "swiper-item-active" : ""}`}>
                <View className="swiper-item-box">
                  <Image className='card-item-bg' src={fullImgUrl(setting.home_tip)} onClick={() => this.goMyCard()} />
                  <Image onClick={this.close} className="colse-card" src={CloseIcon} />
                </View>
              </SwiperItem>
            }
          </Swiper>
        }
      </View>
    );
  }
}
